<?php

namespace common\controller;

use app\common\model\Admin;
use app\common\model\AdminRule;
use common\exception\ExceptionEmun;
use common\exception\MemberException;
use common\exception\ThrowException;
use common\token\Token;
use think\App;

/**
 * Class AdminAuthController
 * @package common\controller
 */
class AdminAuthController extends TokenController
{
    /**
     * @var array 设置Ture控制器方法全局跳过权限验证,可以是数组或者字符串
     */
    protected $no_auth = [];

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        if (!empty($this->no_token) && check_mixed_exist($this->no_token, $this->request->action())) {
            return true;
        }
        // 检查账号有效性
        $userInfo = Token::instance()->getUserInfo();
        if ($userInfo['status'] != 1) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 103, 'error' => '账号已被删除或禁用']));
        }
        $this->_checkRight();
        $GLOBALS['userInfo'] = $userInfo;
        $this->app = $app;
    }

    /**
     * 使用权限验证
     * @param $member_info
     */
    private function _checkRight()
    {
        $module = strtolower($this->request->module());
        $controller = strtolower($this->request->controller());
        $action = $this->request->action();
        $admin_info = Token::instance()->getUserInfo();
        $rule_list = AdminRule::instance()->getUrlRuleList($module, $controller, $action);
        $user_rule_list = (Admin::instance())->getRuleList($admin_info);
        $user_rule_id_arr = $user_rule_list->column(AdminRule::instance()->getPk());
        $url_rule_id_arr = $rule_list->column(AdminRule::instance()->getPk());
        if (array_intersect($url_rule_id_arr, $user_rule_id_arr)) {
            return true;
        }
        ExceptionEmun::throwException(MemberException::NO_RIGHT);
        return false;
    }
}
